package com.yuanfeng.payment.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuanfeng.commoms.config.ALiPayConfig;
import com.yuanfeng.commoms.config.WXConfigUtil;
import com.yuanfeng.commoms.config.WXPayConfig;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import com.yuanfeng.payment.dto.FXCommonDTO;
import com.yuanfeng.payment.dto.ThirdAuthReturnDTO;
import com.yuanfeng.payment.dto.WithdrawRequestDTO;
import com.yuanfeng.payment.entity.PayFxAccountEntity;
import com.yuanfeng.payment.entity.PayFxRecordEntity;
import com.yuanfeng.payment.entity.PayFxTradeEntity;
import com.yuanfeng.payment.mapper.PayConfigMapper;
import com.yuanfeng.payment.mapper.PayFxAccountMapper;
import com.yuanfeng.payment.mapper.PayFxRecordMapper;
import com.yuanfeng.payment.mapper.PayFxTradeMapper;
import com.yuanfeng.payment.service.PayFxAccountService;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
public class PayFxAccountServiceImpl extends ServiceImpl<PayFxAccountMapper, PayFxAccountEntity>
    implements PayFxAccountService{

    private static final Logger logger = LoggerFactory.getLogger(PayFxAccountServiceImpl.class);

    //商户证书编号
    @Value("${wechatPayserialNo}")
    private  String wechatPayserialNum;
    //商户证书路径（在你本机测试时放你本机路径中的就可以）
    @Value("${privatekeypath}")
    private  String wechatkeyPem;

    private static String wechatPayserialNo;
    private static String privatekeypath;

    @PostConstruct
    public  void getWechatPayserialNo() {
        wechatPayserialNo = this.wechatPayserialNum;
    }
    @PostConstruct
    public  void getPrivatekeypath() {
        privatekeypath = this.wechatkeyPem;
    }


    @Autowired
    private PayFxRecordMapper payFxRecordMapper;
    @Autowired
    private PayFxTradeMapper payFxTradeMapper;
    @Autowired
    private PayConfigMapper payConfigMapper;



    @Override
    public ResponseResult updateUserAuthInfo(ThirdAuthReturnDTO param) {
        UserInfoVO ui = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (ui == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_ILLEGAL);
        }
        int result;
        // 1.查询当前用户蜂币账户是否存在，没有则新增
        PayFxAccountEntity userAccount = this.baseMapper.selectOne(new LambdaQueryWrapper<PayFxAccountEntity>()
                                     .eq(PayFxAccountEntity::getUserId,ui.getUserId()));
        if (null == userAccount) {
            // 2.封装数据并信息
            userAccount = new PayFxAccountEntity(ui.getUserId(), ui.getUserName(), ui.getUserMobile());
            if (null != param.getPlatForm() && param.getPlatForm().equals(CommonType.payPlatFrom.MINI_PROGRAM.getCode())) {
                // 微信用户openid
                userAccount.setMiniWxOpenId(StringUtils.isNotBlank(param.getOpenid()) ? param.getOpenid() : null);
                // 微信用户昵称
                userAccount.setMiniWxUserName(StringUtils.isNotBlank(param.getWxNickname()) ? param.getWxNickname() : null);
                // 微信用户标识
                userAccount.setMiniWxUnionId(StringUtils.isNotBlank(param.getUnionid()) ? param.getUnionid() : null);
            } else {
                // 支付宝用户信息
                userAccount.setAliUserId(StringUtils.isNotBlank(param.getAliUserId()) ? param.getAliUserId() : null);
                // 支付宝用户名
                userAccount.setAliUserName(StringUtils.isNotBlank(param.getAliUserName()) ? param.getAliUserName() : null);
                // 微信用户openid
                userAccount.setWxOpenId(StringUtils.isNotBlank(param.getOpenid()) ? param.getOpenid() : null);
                // 微信用户昵称
                userAccount.setWxUserName(StringUtils.isNotBlank(param.getWxNickname()) ? param.getWxNickname() : null);
                // 微信用户标识
                userAccount.setWxUnionId(StringUtils.isNotBlank(param.getUnionid()) ? param.getUnionid() : null);
            }
            result =  this.baseMapper.insert(userAccount);
        } else {
            if (null != param.getPlatForm() && param.getPlatForm().equals(CommonType.payPlatFrom.MINI_PROGRAM.getCode())) {
                // 存在记录时更新用户授权信息
                PayFxAccountEntity updateGameGroupAccount = new PayFxAccountEntity(userAccount.getId(),
                        userAccount.getUserId(), param.getOpenid(), param.getWxNickname(), param.getUnionid());
                result = this.baseMapper.updateById(updateGameGroupAccount);
            } else {
                // 存在记录时更新用户授权信息
                PayFxAccountEntity updateGameGroupAccount = new PayFxAccountEntity(userAccount.getId(), userAccount.getUserId(),
                        param.getAliUserId(), param.getAliUserName(), param.getOpenid(), param.getWxNickname(), param.getUnionid());
                result = this.baseMapper.updateById(updateGameGroupAccount);
            }
        }
        if (result == 1) {
            // 3.重新查询账户数据
            return ResponseResult.success(userAccount);
        }
        return ResponseResult.fail(2, "更新用户授权信息失败请重新授权");

    }

    @Override
    public ResponseResult withdraw(WithdrawRequestDTO param, HttpServletRequest request) {
        logger.info("GameGroupWithdrawServiceImpl withdraw{}", JSON.toJSONString(param));
        ResponseResult resultResp;
        Map<String, Object> map = new HashMap<>();
        Boolean tiXianStart = false;
        String resStr = null;
        //1.获取用户信息
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (null != userInfo) {
            // 2.防重复请求
            Boolean flag = this.verifyWithdraw(userInfo);
            if (flag) {
                try {
                    // 3.验证用户提现金额
                    resultResp = this.checkWithdrawAmount(param, userInfo);

                    if (resultResp.getCode() == 1) {
                        PayFxAccountEntity payFxAccount = JSON.parseObject(JSON.toJSONString(resultResp.getData()),PayFxAccountEntity.class);
                        // 4.生成充值交易记录
                        String recordId = "R" + DateUtils.getTimeStamp()+ RandomStringUtils.randomNumeric(8);
                        // 5.生成第三方请求记录
                        String thirdPayId = "T" + DateUtils.getTimeStamp()+ RandomStringUtils.randomNumeric(8);
                        // 6.初始化请求参数
                        param = this.initWithdrawRequest(payFxAccount, param, thirdPayId, recordId);
                        // 7.添加交易记录数据
                        this.insertPayRecord(param, userInfo);
                        // 8.添加第三方请求数据
                        this.insertThirdPayInfo(param, userInfo);
                        // 9.请求提现
                        if (param.getPayCode().equals(CommonType.payType.ALI.getCode())) {
                            // 支付宝
                            return  ResponseResult.fail(0, "提现方式错误");
                        } else {
                            // 微信
//                            resultResp = wxTransferServiceImpl.wxTransfer(thirdPayId, withdrawRequest.getWxOpenId(), withdrawRequest.getWxUserName(), withdrawRequest.getTotalMoney(), withdrawRequest.getPlatFrom(), request);
                            Map<String,Object> tixianMap = new HashMap<>();
                            tixianMap.put("transferAmount",param.getTotalMoney().multiply(new BigDecimal(100)));
                            tixianMap.put("openId",param.getWxOpenId());
                            map = weixinTransferBat(tixianMap);
                            if(null != map ){
                                tiXianStart = (Boolean) map.get("start");
                                resStr = (String) map.get("resStr");
                            }
                        }
                        // 11.提现成功更新提现交易记录
                        if (tiXianStart) {
                            String thirdTradeNo = (String) map.get("out_batch_no");
                            resultResp = this.withdrawNotify(recordId, thirdPayId, thirdTradeNo, userInfo.getUserId(), payFxAccount, param);
                            return resultResp;
                        } else {
                            // 12.提现失败保存第三方请求失败码
                            if (null != resStr) {
                                this.updateThirdTrade(thirdPayId, recordId, userInfo.getUserId(), param.getTotalMoney(), payFxAccount, resultResp);
                            }
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    return  ResponseResult.fail(0, "提现异常请联系客服");
                } finally {
                    RedisUtil.remove(YFConfig.YF_FX_WITHDRAW_ + userInfo.getUserId());
                }
            } else {
                return  ResponseResult.fail(0, "您已申请提现,请勿重复操作");
            }
        } else {
            return  ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        return resultResp;
    }

    public void updateThirdTrade(String thirdPayId,String recordId,String userId,BigDecimal totalMoney, PayFxAccountEntity payFxAccount, ResponseResult thirdErrorData) {
        PayFxTradeEntity record = new PayFxTradeEntity(null,null);
        // 第三方交易请求单号
        record.setThirdPayId(thirdPayId);
        // 错误码
        record.setErrorCode(String.valueOf(thirdErrorData.getCode()));
        // 错误说明
        record.setErrorMsg(thirdErrorData.getMessage());
        // 回调时间
        record.setNotifyTime(DateUtils.getNowDate());
        // 更新时间
        record.setUpdateTime(DateUtils.getNowDate());

        if (thirdErrorData.getCode()!=CommonType.commonStatus.NO.getCode()) {
            // 如果是系统繁忙错误 冻结用户提现金额，防止用户做其他操作，最后蜂币又提现成功了
            PayFxAccountEntity updateGameGroupAccount = new PayFxAccountEntity(userId, totalMoney,totalMoney);
            this.baseMapper.subUserAccount(updateGameGroupAccount);
            // 更新交易金额更新记录
            PayFxRecordEntity fxRecord = new PayFxRecordEntity(recordId, payFxAccount.getVkAccount(), payFxAccount.getVkAccount().subtract(totalMoney));
            payFxRecordMapper.updateById(fxRecord);
        } else {
            //1. 如果是其他错误  则更新状态为提现失败
            record.setTradeStatus(2);
            // 2.更新蜂币交易记录状态为提现失败
            PayFxRecordEntity fxRecord = new PayFxRecordEntity(recordId, CommonType.recordStatus2.WITHDRAW_CANCEL.getCode(), CommonType.recordStatus2.WITHDRAW_CANCEL.getDesc());
            payFxRecordMapper.updateById(fxRecord);
        }
        payFxTradeMapper.updateById(record);
    }




    @Transactional(rollbackFor = Exception.class)
    public ResponseResult withdrawNotify(String recordId, String thirdPayId, String thirdTradeNo, String userId, PayFxAccountEntity payFxAccount, WithdrawRequestDTO withdrawRequest) {

        try {
            // 1.更新用户蜂币余额
            PayFxAccountEntity updateUserAccount = new PayFxAccountEntity(userId, withdrawRequest.getTotalMoney());
            int result = this.baseMapper.subUserAccount(updateUserAccount);
            // 2.更新蜂币交易记录
            PayFxRecordEntity gameGroupRecord = new PayFxRecordEntity(recordId, payFxAccount.getVkAccount(), payFxAccount.getVkAccount().subtract(withdrawRequest.getTotalMoney()), CommonType.recordStatus2.DEAL_FINISHED.getCode(),"提现成功", DateUtils.getNowDate());
            int recordResult = payFxRecordMapper.updateById(gameGroupRecord);
            // 3.更新第三方提现记录
            PayFxTradeEntity record = new PayFxTradeEntity(null,null);
            // 第三方交易请求单号
            record.setThirdPayId(thirdPayId);
            // 第三方交易单号
            record.setThirdTradeNo(thirdTradeNo);
            // 支付状态
            record.setTradeStatus(CommonType.commonStatus.YES.getCode());
            // 回调时间
            record.setNotifyTime(DateUtils.getNowDate());
            // 更新时间
            record.setUpdateTime(DateUtils.getNowDate());
            int tradeResult = payFxTradeMapper.updateById(record);
            if(result == recordResult && result == tradeResult && result == 1){
                return ResponseResult.success("提现成功");
            }else {
                return ResponseResult.fail(0, "更新用户账户失败");
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            // 操作失败手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseResult.fail(0, "更新用户账户失败");
        }
    }

    /**
     * 验证用户当前是否已存在提现请求
     *
     * @param userInfo
     * @return
     */
    private Boolean verifyWithdraw(UserInfoVO userInfo) {
        String key = YFConfig.YF_FX_WITHDRAW_ + userInfo.getUserId();
        return RedisUtil.getLock(key, RedisUtil.EXRP_DAY);
    }

    public  Map<String,Object> weixinTransferBat(Map<String,Object> map){
        Map<String,Object> resultMap  = new HashMap<>();
        if( null != map && null != map.get("openId") && null != map.get("transferAmount")){
            //查询支付配置信息
            selectYFPayConfig();
            //商户号
            String mchid = WXPayConfig.MCH_ID;
            //申请商户号的appid或商户号绑定的appid（企业号corpid即为此appid）
            String appId =  WXPayConfig.Applet_APP_ID;
            //用户在直连商户应用下的用户标示
            String openId = map.get("openId").toString();
            System.out.println(WXPayConfig.Applet_APP_ID);

            Map<String, Object> postMap = new HashMap<String, Object>();

            //商家批次单号 长度 1~32
            String outNo = IdUtil.getSnowflake(0, 0).nextIdStr();

            postMap.put("appid", appId);
            postMap.put("out_batch_no", outNo);
            //该笔批量转账的名称
            postMap.put("batch_name", "分销提现");
            //转账说明，UTF8编码，最多允许32个字符
            postMap.put("batch_remark", "分销提现");
            //转账金额单位为“分”。 总金额
            postMap.put("total_amount", map.get("transferAmount"));
            //。转账总笔数
            postMap.put("total_num", 1);


            List<Map> list = new ArrayList<>();
            Map<String, Object> subMap = new HashMap<>(4);
            //商家明细单号
            subMap.put("out_detail_no", outNo);
            //转账金额
            subMap.put("transfer_amount", map.get("transferAmount"));
            //转账备注
            subMap.put("transfer_remark", "分销提现");
            //用户在直连商户应用下的用户标示
            subMap.put("openid", openId);
//    subMap.put("user_name", RsaCryptoUtil.encryptOAEP(userName, x509Certificate));
            list.add(subMap);
            postMap.put("transfer_detail_list", list);
            logger.info(wechatPayserialNo);
            logger.info(privatekeypath);
            //发起转账操作
            String resStr = WeiXinHttpUtil.postTransBatRequest(
                    "https://api.mch.weixin.qq.com/v3/transfer/batches",
                    JsonUtils.toString(postMap),
                    wechatPayserialNo,
                    mchid,
                    privatekeypath);
            resultMap = JsonUtils.string2Obj(resStr,Map.class);
            System.out.println(resStr);
            if(null != resultMap && null != resultMap.get("out_batch_no") && null != resultMap.get("batch_id")){
                //提现成功
                resultMap.put("start",true);
                resultMap.put("resStr",resStr);
                return resultMap;
            }
            resultMap.put("resStr",resStr);
            resultMap.put("start",false);
            return resultMap;
        }
        resultMap.put("start",false);
        return resultMap;
    }


    public void selectYFPayConfig() {

        String paymentMode = "00";//微信 pc  h5
        Map<String, String> outMap = payConfigMapper.selectYfPayConfig(paymentMode);
        WXPayConfig.API_KEY=outMap.get("appAPIKey").toString();
        WXPayConfig.APP_SECRET=outMap.get("appSecret").toString();
        WXPayConfig.MCH_ID=outMap.get("appMCHId").toString();
        WXPayConfig.APP_ID=outMap.get("appID").toString();
        WXPayConfig.NOTIFY_URL=outMap.get("notifyUrl").toString();
        WXPayConfig.REDIRECT_URL=outMap.get("redirectUrl").toString();
        WXPayConfig.weChatWapPath=outMap.get("weChatPcPath").toString();
        WXPayConfig.PLUS_NOTIFY_URL=outMap.get("plusNotifyUrl").toString();

        //微信app
        WXConfigUtil.KEY=outMap.get("appAPIKey").toString();
        WXConfigUtil.APP_SECRET=outMap.get("appSecret").toString();
        WXConfigUtil.MCH_ID=outMap.get("appMCHId").toString();
        WXConfigUtil.APP_ID=outMap.get("appID").toString();
        WXConfigUtil.NOTIFY_URL_APP= outMap.get("notifyUrl").toString();

        String paymentMode2 = "02";//微信小程序
        Map<String, String> outMap2 = payConfigMapper.selectYfPayConfig(paymentMode2);
        WXPayConfig.Applet_APP_ID=outMap2.get("appID").toString();
        WXPayConfig.Applet_APP_SECRET= outMap2.get("appSecret").toString();


        String paymentMode3 = "03";//支付宝
        outMap = payConfigMapper.selectYfPayConfig(paymentMode3);
        if(null != outMap && !outMap.isEmpty()) {
            ALiPayConfig.URL = outMap.get("gatewayURL").toString();
            ALiPayConfig.APPID = outMap.get("appID").toString();
            ALiPayConfig.sellerId = outMap.get("appMCHId").toString();
            ALiPayConfig.RSA_PRIVATE_KEY = outMap.get("appAPIKey").toString();
            ALiPayConfig.CERT_PATH = outMap.get("cert_public_key_res2").toString();
            ALiPayConfig.ROOT_CERT_PATH = outMap.get("cert_root_key").toString();
            ALiPayConfig.ALIPAY_PUBLIC_CERT_PATH = outMap.get("cert_app_public_key").toString();
            ALiPayConfig.shopping_notify_url = outMap.get("shoppingNotifyUrl").toString();
            ALiPayConfig.shopping_notify_url_h5 = outMap.get("rechargeNotifyUrl2").toString();
            ALiPayConfig.shopping_return_url_pc = outMap.get("shoppingReturnUrlPc").toString();
            ALiPayConfig.plus_notify_url = outMap.get("plusNotifyUrl").toString();
        }
    }



    public PayFxRecordEntity insertPayRecord(FXCommonDTO fxCommon, UserInfoVO userInfo) {
        PayFxRecordEntity gameGroupRecord = new PayFxRecordEntity(null,0,null);
        // 交易单号
        gameGroupRecord.setRecordId(fxCommon.getRecordId());
        // 用户ID
        gameGroupRecord.setUserId(userInfo.getUserId());
        // 用户名
        gameGroupRecord.setUserName(userInfo.getUserName());
        // 交易金额
        gameGroupRecord.setRecordAmount(fxCommon.getTotalMoney());
        // 交易状态 1:待处理 2交易完成 3交易取消
        gameGroupRecord.setRecordStatus(fxCommon.getRecordStatus());
        // 账户类型 1微客佣金  2员工佣金
        gameGroupRecord.setRecordType(fxCommon.getRecordType());
        // 交易类型
        gameGroupRecord.setTradeTypeId(fxCommon.getTradeTypeId());
        // 金额正负判断(1:+0:-)
        gameGroupRecord.setPlusOrMinus(fxCommon.getPlusOrMinus());
        // 支付方式1支付宝 2微信
        gameGroupRecord.setPayCode(fxCommon.getPayCode());
        // 提现的支付宝账户信息
        gameGroupRecord.setAliUserId(StringUtils.isBlank(fxCommon.getAliUserId())?null:fxCommon.getAliUserId());
        gameGroupRecord.setAliUserName(StringUtils.isBlank(fxCommon.getAliUserName())?null:fxCommon.getAliUserName());
        // 提现的微信账户信息
        gameGroupRecord.setWxOpenId(StringUtils.isBlank(fxCommon.getWxOpenId())?null:fxCommon.getWxOpenId());
        gameGroupRecord.setWxUserName(StringUtils.isBlank(fxCommon.getWxUserName())?null:fxCommon.getWxUserName());
        // 支付来源
        gameGroupRecord.setPayFrom(fxCommon.getPlatFrom());
        // 描述
        String payName =CommonType.payCode.getByCode(fxCommon.getPayCode());
        gameGroupRecord.setRecordName("提现至"+payName);
        // 状态说明
        gameGroupRecord.setRecordStatusName("提现待处理");
        // 操作日期
        gameGroupRecord.setRecordDate(DateUtils.parseDateSDF(DateUtils.getNowDay()));
        // 创建时间
        gameGroupRecord.setCreateTime(DateUtils.getNowDate());
        // 更新时间
        gameGroupRecord.setUpdateTime(DateUtils.getNowDate());
        payFxRecordMapper.insert(gameGroupRecord);
        return gameGroupRecord;
    }


    public PayFxTradeEntity insertThirdPayInfo(FXCommonDTO fxCommon, UserInfoVO userInfo) {
        PayFxTradeEntity gameGroupTrade = new PayFxTradeEntity(0, fxCommon.getPayCode());
        // 第三方交易请求单号
        gameGroupTrade.setThirdPayId(fxCommon.getThirdPayId());
        // 交易单号
        gameGroupTrade.setRecordId(fxCommon.getRecordId());
        // 用户id
        gameGroupTrade.setUserId(userInfo.getUserId());
        // 用户名
        gameGroupTrade.setUserName(userInfo.getUserName());
        // 用户名
        gameGroupTrade.setTotalMoney(fxCommon.getTotalMoney());
        // 交易手续费
        gameGroupTrade.setTradeRate(fxCommon.getTaxAmount());
        // 交易描述
        gameGroupTrade.setTradeDesc(fxCommon.getTradeDesc());
        // 交易类型
        gameGroupTrade.setTradeTypeId(fxCommon.getTradeTypeId());
        // 创建时间
        gameGroupTrade.setCreateTime(DateUtils.getNowDate());
        // 更新时间
        gameGroupTrade.setUpdateTime(DateUtils.getNowDate());
        payFxTradeMapper.insert(gameGroupTrade);
        return gameGroupTrade;
    }


    /**
     * 初始化请求参数
     *
     * @param withdrawRequest
     * @param thirdPayId
     * @param recordId
     * @return
     */
    private WithdrawRequestDTO initWithdrawRequest(PayFxAccountEntity gameGroupAccount, WithdrawRequestDTO withdrawRequest, String thirdPayId, String recordId) {
        withdrawRequest.setThirdPayId(thirdPayId);
        withdrawRequest.setRecordId(recordId);
        withdrawRequest.setRecordType(1);
        withdrawRequest.setRecordStatus(CommonType.recordStatus2.WAITING_FOR_DISPOSE.getCode());
        withdrawRequest.setTradeDesc("提现");
        withdrawRequest.setTradeTypeId(2);
        withdrawRequest.setPlusOrMinus(0);
        // 支付宝提现账户信息
        if (withdrawRequest.getPayCode().equals(CommonType.payType.ALI.getCode())) {
            withdrawRequest.setAliUserId(gameGroupAccount.getAliUserId());
            withdrawRequest.setAliUserName(gameGroupAccount.getAliUserName());
        } else {
            if (null != withdrawRequest.getPlatFrom() && withdrawRequest.getPlatFrom().equals(CommonType.payPlatFrom.MINI_PROGRAM.getCode())) {
                // 小程序微信提现账户信息
                withdrawRequest.setWxOpenId(gameGroupAccount.getMiniWxOpenId());
                withdrawRequest.setWxUserName(gameGroupAccount.getMiniWxUserName());
            } else {
                // 微信提现账户信息
                withdrawRequest.setWxOpenId(gameGroupAccount.getWxOpenId());
                withdrawRequest.setWxUserName(gameGroupAccount.getWxUserName());
            }
        }
        return withdrawRequest;
    }

    /**
     * 验证提现金额
     *
     * @param withdrawRequest
     * @param userInfo
     */
    private ResponseResult checkWithdrawAmount(WithdrawRequestDTO withdrawRequest, UserInfoVO userInfo) {
        ResponseResult resultResp;
        if (null != withdrawRequest.getTotalMoney() && withdrawRequest.getTotalMoney().compareTo(BigDecimal.ZERO) > 0) {
            if (withdrawRequest.getPayCode().equals(CommonType.payType.ALI.getCode())) {
                if (withdrawRequest.getTotalMoney().compareTo(ALiPayConfig.MIN_AMOUNT) < 0) {
                    return ResponseResult.fail(0, "支付宝提现金额不可低于0.1元");
                }
            } else {
                if (withdrawRequest.getTotalMoney().compareTo(WXPayConfig.MIN_AMOUNT) < 0) {
                    return ResponseResult.fail(0, "微信提现金额不可低于0.3元");
                }
            }
            // 1.查询用户账户
            PayFxAccountEntity userAccountAccount = this.queryUserAccount(userInfo);
            if (null == userAccountAccount || userAccountAccount.getVkAccount().compareTo(BigDecimal.ZERO) <= 0) {
                // 2.微客余额不足不可提现
                return ResponseResult.fail(0, "用户余额不足,无法提现!");
            } else if (withdrawRequest.getTotalMoney().compareTo(userAccountAccount.getVkAccount()) > 0) {
                // 3.提现金额大于微客余额  不可提现
                return ResponseResult.fail(0, "您的账户余额不足,请确认提现金额后重试");
            } else {
                // 4.金额验证成功后,验证用户提现授权信息
                if (withdrawRequest.getPayCode().equals(CommonType.payType.ALI.getCode())) {
                    if (StringUtils.isBlank(userAccountAccount.getAliUserId())) {
                        // 用户未授权
                        return ResponseResult.fail(0, "用户未授权");
                    } else {
                        // 验证成功
                        resultResp = ResponseResult.success(userAccountAccount);
                    }
                } else if (withdrawRequest.getPayCode().equals(CommonType.payType.WX.getCode())) {
                    if (null != withdrawRequest.getPlatFrom() && withdrawRequest.getPlatFrom().equals(CommonType.payPlatFrom.MINI_PROGRAM.getCode())) {
                        if (StringUtils.isBlank(userAccountAccount.getMiniWxOpenId())) {
                            // 用户未授权
                            resultResp = ResponseResult.fail(0, "用户未授权");
                        } else {
                            // 验证成功
                            resultResp = ResponseResult.success(userAccountAccount);
                        }
                    } else {
                        if (StringUtils.isBlank(userAccountAccount.getWxOpenId())) {
                            // 用户未授权
                            resultResp = ResponseResult.fail(0, "用户未授权");
                        } else {
                            // 验证成功
                            resultResp = ResponseResult.success(userAccountAccount);
                        }
                    }
                } else {
                    // 验证成功
                    resultResp = ResponseResult.fail(0, "提现金额不可小于0,请确认后重试");
                }
            }
        } else {
            // 提现金额不可小于等于0
            resultResp = ResponseResult.fail(0, "提现金额不可小于0,请确认后重试");
        }
        return resultResp;
    }


    public PayFxAccountEntity queryUserAccount(UserInfoVO userInfo) {
        PayFxAccountEntity gameGroupAccount =this.baseMapper.selectOne(new LambdaQueryWrapper<PayFxAccountEntity>()
                                        .eq(PayFxAccountEntity::getUserId,userInfo.getUserId()));
        if (null == gameGroupAccount) {
            // 1.如果用户没有账户信息则添加一条数据
            // 1.封装数据并插入
            PayFxAccountEntity fxAccount = new PayFxAccountEntity(userInfo.getUserId(), userInfo.getUserName(), userInfo.getUserMobile());
            this.baseMapper.insert(fxAccount);
            // 2.重新查询账户数据
            gameGroupAccount =this.baseMapper.selectOne(new LambdaQueryWrapper<PayFxAccountEntity>()
                    .eq(PayFxAccountEntity::getUserId,userInfo.getUserId()));
            return  gameGroupAccount;
        }
        return gameGroupAccount;
    }

}




